const moment = require("moment");
var md5 = require("md5");


const PagerHelper = {

    SuccessRes: function (data) {
        return {
            resultCode: 1000,
            resultData: data,
            resultMsg: "",
        };
    },
    FailRes: function (msg, code) {
        return {
            resultCode: code || 0,
            resultData: null,
            resultMsg: msg || "操作失败",
        };
    },
    StringIsNullOrEmpty: function (str) {
        str = str || "";


        var b = str.length == 0;

        return b;
    },

    checkUserPermission: async (ctx) => {


        // 1. 有没有appKey

        var appKey = "";
        if (!ctx.request.body.header) {
            ctx.body = PagerHelper.FailRes("appKey缺失", 1001);
            return false;
        }
        appKey = ctx.request.body.header["appKey"] || "";
        sign = ctx.request.body.header["sign"] || "";

        if (appKey.length == 0) {
            ctx.body = PagerHelper.FailRes("appKey缺失", 1001);
            return false;
        }

        if (sign.length == 0) {
            ctx.body = PagerHelper.FailRes("请添加签名", 1004);
            return false;
        }

        //如果有token就把用户信息带上
        const memberMap = require("../auth/member.json");

        if (!memberMap.hasOwnProperty(appKey)) {
            ctx.body = PagerHelper.FailRes("appKey不存在", 1002);
            return false;
        }

        var appInfo = memberMap[appKey];


        //2.授权期限
        var dt = new Date();
        if (
            dt < new Date(appInfo.validDateStart + " 00:00:00") ||
            dt > new Date(appInfo.validDateEnd + " 23:59:59")
        ) {
            ctx.body = PagerHelper.FailRes("授权过期", 1003);
            return false;
        }

        //3.有效时间范围内 2分钟 要求两方服务器时间正常
        var dt2 = moment();

        var reqTime = ctx.request.body.header["reqTime"];
        var spanMin = dt2.diff(moment(reqTime), "minute");


        if (spanMin < -2 || spanMin > 2) {
            ctx.body = PagerHelper.FailRes("请求时效过期", 1004)
            return false
        }

        var _md5 = md5(ctx.request.body.body + appInfo.appSecret + reqTime);

        if (sign != "88888888" && _md5 != sign) {
            ctx.body = PagerHelper.FailRes("签名验证失败", 1005);
            return false;
        }


        return true;
    },
};

module.exports = PagerHelper;
